package com.example.end.musicplayer;

import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.example.end.musicplayer.Save.PropertyBean;
import com.example.end.musicplayer.data.Music;
import com.example.end.musicplayer.data.MusicList;
import com.example.end.musicplayer.data.MusicService;

public class MainActivity extends AppCompatActivity {

    // 显示组件
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView list;
    //歌曲列表对象
    private ArrayList<Music> musicArrayList;
    // 当前歌曲的序号，下标从0开始
    private int number = 0;
    //播放状态
    private int status;
    //状态改变时的广播接收器
    private StatusChangedReceiver receiver;
    private RelativeLayout root_Layout;
    private Menu menu;
    private TextView textView;
    private TextView text_Current;
    private TextView text_Duration;
    private SeekBar seekBar;
    private Handler seekBarHandler;
    //当前歌曲的持续时间和当前位置，作用于进度条
    private int duration;
    private int time;
    //进度条控制常量
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;
    //定义播放模式常量
    private static final int mode_list_sequence=0;
    private static final int mode_single_cycle=1;
    private static final int mode_list_cycle=2;
    private static final int mode_random=3;
    private int playmode;
    //退出判断标记
    private static boolean isExit=false;
    //音量控制
    private TextView t_vol;
    private SeekBar s_vol;
    //睡眠模式相关组件，标识常量
    private ImageView sleep_img;
    private Timer sleep_time;
    private static final boolean NOSLEEP=false;
    private static final boolean ISSLEEP=true;
    //默认睡眠时间
    private int sleepMinute=20;
    //标记是否打开睡眠模式
    private static boolean sleepmode;
    @Override
    protected void onCreate(Bundle savedInstanceState) {//生命周期，当活动创建时执行
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();
        registerListeners();
        initMusicList();
        initListView();
        checkMusicfile();
        duration=0;
        time=0;
        //绑定当状态改变时接收广播的接收器
        bindStatusChangedReceiver();
        initSeekBarHandler();
        startService(new Intent(this,MusicService.class));
        status=MusicService.command_stop;

        //默认播放模式
        playmode=MainActivity.mode_list_sequence;
        //默认睡眠模式为关闭状态
        sleepmode=MainActivity.NOSLEEP;
    }
    private void bindStatusChangedReceiver()
    {
        receiver=new StatusChangedReceiver();
        IntentFilter filter=new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver,filter);
    }
    // 获取按钮
    private void findViews() {
        imgBtn_Previous = (ImageButton) findViewById(R.id.imageButton1);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.imageButton2);
        imgBtn_Stop = (ImageButton) findViewById(R.id.imageButton3);
        imgBtn_Next = (ImageButton) findViewById(R.id.imageButton4);
        list = (ListView) findViewById(R.id.listView1);
        root_Layout=(RelativeLayout)findViewById(R.id.relativeLayout1);
        textView=(TextView)findViewById(R.id.textView);
        text_Current = (TextView) findViewById(R.id.textView1);
        text_Duration = (TextView) findViewById(R.id.textView2);
        seekBar=(SeekBar)findViewById(R.id.seeBar1);
        t_vol=(TextView)findViewById(R.id.volumeText);
        s_vol=(SeekBar)findViewById(R.id.volumeSeekBar);
        sleep_img=(ImageView)findViewById(R.id.sleep);
    }

    //为组件设置监听
    private void registerListeners() {
        imgBtn_Previous.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                switch (playmode)
                {
                    case mode_random:
                        sendBroadcastOnCommand(MusicService.command_random);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.command_previous);
                        break;
                }
            }
        });
        imgBtn_PlayOrPause.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                //根据状态发送广播，执行对应的命令
                switch (status)
                {
                    case MusicService.status_playing:
                        sendBroadcastOnCommand(MusicService.command_pause);
                        break;
                    case MusicService.status_paused:
                        sendBroadcastOnCommand(MusicService.command_resume);
                        break;
                    case MusicService.command_stop:
                        sendBroadcastOnCommand(MusicService.command_play);
                        break;
                    default:
                        break;
                }
            }
        });
        imgBtn_Stop.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
               sendBroadcastOnCommand(MusicService.command_stop);
            }
        });
        imgBtn_Next.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                switch (playmode)
                {
                    case mode_random:
                        sendBroadcastOnCommand(MusicService.command_random);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.command_next);
                        break;
                }
            }
        });
        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                number = position ;
                sendBroadcastOnCommand(MusicService.command_play);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //进度条暂停移动
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(status!=MusicService.status_stopped) {
                    time=seekBar.getProgress();
                    //更新文本
                    text_Current.setText(formatTime(time));
                    //发送广播到MusicService,执行跳转
                    sendBroadcastOnCommand(MusicService.command_seek_to);
                }
                if(status == MusicService.status_playing){
                    //发送广播给MusicService，执行跳转
                    sendBroadcastOnCommand(MusicService.command_seek_to);
                    //进度条恢复移动
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }
                if(status==MusicService.status_paused){
                    sendBroadcastOnCommand(MusicService.command_seek_to);
                    sendBroadcastOnCommand(MusicService.command_resume);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }
            }
        });
    }
    /**初始化音乐列表对象*/
    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();
        //避免重复添加音乐
        if(musicArrayList.isEmpty())
        {
            //使用ContentProvider,对应ContentResolver
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //总时长
            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

            /**通过mMusicCursor游标遍历数据库，并将Music类对象加载带ArrayList中*/
            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()) {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);

                if (strArtist.equals("<unknown>"))//如果艺术家字段为unknown
                    strArtist = "无艺术家";
                Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                musicArrayList.add(music);
            }
        }
    }
    /**设置适配器并初始化listView*/
    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musicArrayList) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getmusicName());
            map.put("musicArtist", music.getmusicArtist());
            list_map.add(map);
        }

        String[] from = new String[] { "musicName", "musicArtist" };
        int[] to = { R.id.listview_tv_title_item, R.id.listview_tv_artist_item };

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview,from, to);
        list.setAdapter(simpleAdapter);
    }

    /**如果列表没有歌曲，则播放按钮不可用，并提醒用户*/
    private void checkMusicfile()
    {
        if (musicArrayList.isEmpty()) {
            imgBtn_Next.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Previous.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件",Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Next.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Previous.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
        }
    }
    @Override
    protected void onResume()
    {
        super.onResume();
        sendBroadcastOnCommand(MusicService.command_check_is_playing);
        PropertyBean propetry=new PropertyBean(MainActivity.this);
        String theme=propetry.getTheme();
        //设置主题
        setTheme(theme);
        audio_control();
        //睡眠模式打开时显示图标，关闭时隐藏图标
        if(sleepmode==MainActivity.NOSLEEP)
        {
            sleep_img.setVisibility(View.VISIBLE);
        }
        else
        {
            sleep_img.setVisibility(View.INVISIBLE);
        }
    }
    //发送命令，控制音乐播放
    private void sendBroadcastOnCommand(int command)
    {
        //用于过滤器IntentFilter识别广播
        Intent intent=new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command",command);
        switch (command)
        {
            case  MusicService.command_play:
                intent.putExtra("number",number);
                break;
            case MusicService.command_previous:
            case MusicService.command_next:
            case MusicService.command_pause:
            case MusicService.command_stop:
            case MusicService.command_resume:
            case MusicService.command_seek_to:
                intent.putExtra("time",time);
                break;
            case MusicService.command_random:
            default:
                break;
        }
        sendBroadcast(intent);//广播发送intent
    }
    //内部类，用于播放器状态改变时接收广播
    class StatusChangedReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String name=intent.getStringExtra("name");
            String artist=intent.getStringExtra("artist");
            //获取播放器状态
            status=intent.getIntExtra("status",-1);
            switch (status)
            {
                case MusicService.status_playing:
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    list.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000L);
                    text_Duration.setText(formatTime(duration));
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                    //设置textview，显示正在播放的歌曲
                    MainActivity.this.setTitle("正在播放"+name+" - "+artist);
                    MainActivity.this.textView.setText(name);
                    break;
                case MusicService.status_paused:
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                    MainActivity.this.setTitle("歌曲is pausing！！！");
                    MainActivity.this.textView.setText(name);
                    break;
                case MusicService.status_stopped:
                    time = 0;
                    duration = 0;
                    text_Current.setText(formatTime(time));
                    text_Duration.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                    MainActivity.this.textView.setText("");
                    break;
                case MusicService.status_completed:
                    number = intent.getIntExtra("number", 0);
                    if(playmode==MainActivity.mode_list_sequence)
                    {
                        if (number == MusicList.getMusicList().size() - 1)
                            sendBroadcastOnCommand(MusicService.status_stopped);
                        else
                            sendBroadcastOnCommand(MusicService.command_next);
                    }
                    else if (playmode==MainActivity.mode_list_cycle)
                    {
                        if (number==MusicList.getMusicList().size()-1)
                        {
                            number=0;
                            sendBroadcastOnCommand(MusicService.command_play);
                        }
                        else
                            sendBroadcastOnCommand(MusicService.command_next);
                    }
                    else if(playmode==MainActivity.mode_single_cycle)
                    {
                        sendBroadcastOnCommand(MusicService.command_play);
                    }
                    else if(playmode==MainActivity.mode_random)
                    {
                        sendBroadcastOnCommand(MusicService.command_random);
                    }
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("");
//                    sendBroadcastOnCommand(MusicService.command_next);
//                    MainActivity.this.textView.setText("");
                    break;
                default:
                    break;
            }
        }
    }
    //设置Activity的主题，包括修改背景图片等等
    private void setTheme(String theme)
    {
        if("彩色".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_color);
        }else if("花朵".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_digit_flower);
        }else if("群山".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_mountain);
        }else if("小狗".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_running_dog);
        }else if("冰雪".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_snow);
        }else if("女孩".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_music_girl);
        }else if("朦胧".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_blur);
        }
    }
    //创建菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        this.getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }
    /*处理菜单点击事件*/
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.menu_theme:
                new AlertDialog.Builder(this)
                        .setTitle("请选择主题").
                        setItems(R.array.theme,
                                new android.content.DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        String theme = PropertyBean.THEMES[which];
                                        MainActivity.this.setTheme(theme);
                                        PropertyBean property = new PropertyBean(MainActivity.this);
                                        property.setAndSaveTheme(theme);
                                    }
                                }).show();
                break;
            case R.id.menu_about:
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("MusicPlayer")
                        .setMessage(R.string.about2).show();
                break;
            case R.id.menu_playmode:
                String []mode=new String[]{"顺序播放","列表播放","单曲循环","随机播放"};
                new AlertDialog.Builder(this)
                        .setTitle("播放模式")
                        .setSingleChoiceItems(mode,playmode
                        ,new DialogInterface.OnClickListener(){
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        playmode=which;
                                    }
                                })
                        .setPositiveButton("确定",new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (playmode)
                                {
                                    case 0:
                                        playmode=MainActivity.mode_list_sequence;
                                        Toast.makeText(getApplicationContext(), R.string.sequence,
                                                Toast.LENGTH_SHORT).show();
                                        break;
                                    case 1:
                                        playmode=MainActivity.mode_list_cycle;
                                        Toast.makeText(getApplicationContext(), R.string.listCycle,
                                                Toast.LENGTH_SHORT).show();
                                        break;
                                    case 2:
                                        playmode=MainActivity.mode_single_cycle;
                                        Toast.makeText(getApplicationContext(), R.string.singleCycle,
                                                Toast.LENGTH_SHORT).show();
                                        break;
                                    case 3:
                                        playmode=MainActivity.mode_random;
                                        Toast.makeText(getApplicationContext(),"随机播放",
                                                Toast.LENGTH_SHORT).show();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }).show();
                break;
            case R.id.menu_sleep:
                showSleepDialog();
                break;
            case R.id.menu_quit:
                //退出程序
                new AlertDialog.Builder(this)
                        .setTitle("提示").
                        setMessage(R.string.quit).setPositiveButton("确定",
                        new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        System.exit(0);
                    }
                }).setNegativeButton("取消",
                        new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private String formatTime(int msec)
    {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }
        if (second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }
    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进一秒
                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                        break;
                }
            }
        };
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int progress;
        switch (keyCode)
        {
            case KeyEvent.KEYCODE_BACK:
                exitByDoubleClick();
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                progress=s_vol.getProgress();
                if(progress!=0)
                {
                    s_vol.setProgress(progress-1);
                }
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                progress=s_vol.getProgress();
                if(progress!=s_vol.getMax())
                {
                    s_vol.setProgress(progress+1);
                }
                return true;
            default:
                break;
        }
        return false;
    }
    private void exitByDoubleClick()
    {
        Timer timer=null;
        if(isExit==false)
        {
            isExit=true;
            Toast.makeText(this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
            timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit=false;
                }
            },2000);
        }
        else
        {
            System.exit(0);
        }
    }
    private void audio_control()
    {
        //获取音量管理器
        final AudioManager audioManager=(AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        //设置滑动条最大值
        final int max_progress=audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        s_vol.setMax(max_progress);
        //获取当前音量
        int progress=audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        s_vol.setProgress(progress);
        t_vol.setText("音量："+(progress*100/max_progress)+"%");
        s_vol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                t_vol.setText("音量："+(progress*100)/max_progress+"%");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,AudioManager.FLAG_PLAY_SOUND);
            }
        });
    }

    private void showSleepDialog() {
        //加载布局
        final View userview=this.getLayoutInflater().inflate(R.layout.dialog,null);
        //通过view类的findViewById获取组件
        final TextView tw_minute=(TextView)userview.findViewById(R.id.dialog_tw);
        final Switch switch1=(Switch)userview.findViewById(R.id.dialog_switch);
        final SeekBar seekBar=(SeekBar)userview.findViewById(R.id.dialog_seekBar);

        tw_minute.setText("睡眠于："+sleepMinute+"分钟");
        //根据当前的睡眠状态来判断switch的状态
        if(sleepmode==MainActivity.ISSLEEP)
        {
            switch1.setChecked(true);
        }
        seekBar.setMax(60);
        seekBar.setProgress(sleepMinute);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                sleepMinute=progress;
                tw_minute.setText("睡眠于："+sleepMinute+"分钟");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sleepmode=isChecked;
            }
        });
        //定义定时器任务
        final TimerTask timerTask=new TimerTask() {
            @Override
            public void run() {
                System.exit(0);
            }
        };
        //定义对话框以及初始化
        final AlertDialog.Builder dialog=new AlertDialog.Builder(this);
        dialog.setTitle("设置睡眠时间（0-60分钟）");
        //设置布局
        dialog.setView(userview);
        //设置取消按钮事件
        dialog.setNegativeButton("取消",new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //设置重置按钮事件
        dialog.setNeutralButton("重置",new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(sleepmode==MainActivity.ISSLEEP)
                {
                    timerTask.cancel();//?????
                    sleep_time.cancel();//?????
                }
                sleepmode=MainActivity.NOSLEEP;
                sleepMinute=20;
                sleep_img.setVisibility(View.INVISIBLE);
            }
        });
        //设置确定按钮事件
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(sleepmode==MainActivity.ISSLEEP)
                {
                    sleep_time=new Timer();
                    int time=seekBar.getProgress();
                    //启动任务，time*1000*60ms后执行
                    sleep_time.schedule(timerTask,time*60*1000);
                    sleep_img.setVisibility(View.VISIBLE);
                }
                else if(sleepmode==MainActivity.NOSLEEP)
                {
                    timerTask.cancel();//取消定时任务
                    if(sleep_time!=null){
                        sleep_time.cancel();
                    }
                    dialog.dismiss();
                    sleep_img.setVisibility(View.INVISIBLE);
                }
            }
        });
        dialog.show();
    }
}

//    // 媒体播放类
//    private MediaPlayer player = new MediaPlayer();
//
//
//    /** 读取音乐文件 */
//    private void load(int number) {
//        try {
//            player.reset();
//            player.setDataSource(MusicList.getMusicList().get(number).getmusicPath());
//            player.prepare();
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//    }
//    /** 播放音乐 */
//    private void play(int number) {
//        // 停止当前播放
//        if (player != null && player.isPlaying()) {
//            player.stop();
//        }
//        load(number);
//        player.start();
//    }
//    /** 暂停音乐 */
//    private void pause() {
//        if (player.isPlaying()) {
//            player.pause();
//        }
//    }
//    /** 停止播放 */
//    private void stop() {
//        player.stop();
//    }
//    /** 恢复播放（暂停之后） */
//    private void resume() {
//        player.start();
//    }
//    /** 重新播放（播放完成之后） */
//    private void replay() {
//        player.start();
//    }
//
//    //播放下一曲
//    private void moveNumberToNext() {
//        // 判断是否到达了列表底端
//        if ((number ) == MusicList.getMusicList().size()-1) {
//            Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_reach_bottom),Toast.LENGTH_SHORT).show();
//        } else {
//            ++number;
//            play(number);
//        }
//    }
//
//    //播放上一曲
//    private void moveNumberToPrevious() {
//        // 判断是否到达了列表顶端
//        if (number == 0) {
//            Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_reach_top),Toast.LENGTH_SHORT).show();
//        } else {
//            --number;
//            play(number);
//        }
//    }

